<template>
	<view class="container">
		    <uni-drawer ref="showRight" mode="left" :mask-click="true" :width="drawerWidth">
				<scroll-view style="height: 100%;" scroll-y="true">
					<uni-list>
						<uni-list-item v-for="(item, index) in tableData" :key="index" :title="item.name" badge-text="12" @click="chooseOne(index)" clickable></uni-list-item>
					</uni-list>
				</scroll-view>
			</uni-drawer>
			<uni-nav-bar leftWidth="148rpx" rightWidth="200rpx"class="uni-mt-10">
				<block slot="left">
					<view class="city" @click="showDrawer" >
						<view>
							<text class="uni-nav-bar-text" style="font-size:30rpx">{{ choosePeople }}</text>
						</view>
						<uni-icons type="arrowdown" color="#666" size="18" />
					</view>
				</block>
				<view class="input-view">
					<uni-datetime-picker
					type="date" 
					:clear-icon="false" 
					v-model="queryParams.dateStr"
					@change="dateChange"/>
				</view>
				<block slot="right">
					<view class="weeks"  style="font-size:26rpx">
						第{{ queryParams.weeks }}周
					</view>
					<view class="city" @click="downloadTemplate" >
						<view>
							<text class="uni-nav-bar-text--underline"  style="font-size:26rpx">导出</text>
						</view>
						<uni-icons type="download-filled" color="#666" size="18" />
					</view>
				</block>
			</uni-nav-bar>
			<zySegmented :current="current" :values="items" @onClickItem="onClickItem" styleType="text" activeColor="#4077f4"></zySegmented>
			
			<uni-section style="margin-top:70rpx;"class="mb-10" :title="'共' + total + '条'" type="line"></uni-section>
			<image class="image" :src="noData" mode="widthFix" v-if="total == 0"></image>
			<text class="uni-body noData" v-if="total == 0">暂无数据</text>
			<view >
				<uni-card :title="parseTime(item.date,'{m}月{d}日（星期{a}）')" :is-full="false" :is-shadow="true"
						  v-for="(item, index) in childData" :key="index">
					<uni-row>
						<view class="content">
							<uni-section title="上午:" title-font-size="16px" type="square" style="line-height: 14px" v-if="!item.allday">
								<template v-slot:right>
									<text style="width: 440rpx;font-size: 15px;display: inline-block;line-height: 40rpx;text-align: right;">{{ item.morning }}</text>
								</template>
							</uni-section>
							<uni-section title="下午:" title-font-size="16px" type="square" style="line-height: 14px" v-if="!item.allday">
								<template v-slot:right>
									<text style="width: 440rpx;font-size: 15px;display: inline-block;line-height: 40rpx;text-align: right;">{{ item.afternoon }}</text>
								</template>
							</uni-section>
							<uni-section title="全天:" title-font-size="16px" type="square" style="line-height: 14px" v-if="item.allday">
								<template v-slot:right>
									<text style="width: 440rpx;font-size: 15px;display: inline-block;line-height: 40rpx;text-align: right;">{{ item.allday }}</text>
								</template>
							</uni-section>
						</view>
						
						<uni-col :span="12" :push="4" @click.native="handleUpdate(item)">
							<uni-icons type="compose" size="20" color="#999"></uni-icons>
							<text class="card-actions-item-text">修改</text>
						</uni-col>
						<uni-col :span="12" :push="4" @click.native="handleDelete(item)">
							<uni-icons type="trash" size="20" color="#999"></uni-icons>
							<text class="card-actions-item-text">删除</text>
						</uni-col>
					</uni-row>
				</uni-card>
			</view>
		<uni-load-more :status="status" v-if="total > 0"/>
		<addCom :sharePacket="sharePacket" :icon="icon" :iconSize="iconSize" @click.native="addArrange"></addCom>
	</view>
	
</template>

<script>
import {checkPermi} from "@/utils/permission";
import {getDictValue, selectDictLabel,listData,delData} from '@/api/system/dict/data';
import {arrangeApi} from '@/api/module';
import { download } from '@/api/module/download';
import addCom from '@/components/addCom';
import zySegmented from '@/components/zy-segmented-control/zy-segmented-control';

export default {
	components:{
		addCom,
		zySegmented
	},
	data() {
		return {
			choosePeople:"选择",
			items: [],
			current: 0,
			//数据
			tableData: [],
			//加载
			tableLoading: true,
			//统计
			total: 0,

			//查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 266,
				date:null,
				weeks:null,
			},

			status: 'more',
			noData: "/static/images/noData.png",
			imageStyle: {
				height: uni.getSystemInfoSync().windowHeight
			},
			//打开开关、
			sharePacket: {
				isState: false, //默认不显示
				touchstart:false
			},
			icon:"./static/images/addProduct.png",
			iconSize:"width: 85rpx;height: 80rpx;",
			//数据
			childData: [],
			drawerWidth:150,
			//下载参数
			downParams: {
			  date: null,
			  weeks: null,
			  name: '',
			},
		}
	},
	async onLoad(option) {
		//获取下周日期
		this.getNextWeeks();
		//获取数据
		this.getList();
		
		

	},
	onReachBottom() {

		if (this.tableData.length < this.total) {
			this.status = 'loading';
			this.queryParams.pageNum = this.queryParams.pageNum + 1
			this.getList();
		}
		console.log('已触底');
	},
	onReady() {

	},
	methods: {
		/* getNextWeeks(){
			//获取下周日期
			let currentDate = new Date();
			let currentDateStr = this.parseTime(currentDate);
			this.queryParams.weeks = this.getWeeks(currentDateStr) + 1;
			
			const oneDayMilliseconds = 24 * 60 * 60 * 1000;
			const nextSevenDayTime = currentDate.getTime() + oneDayMilliseconds * 7;
			this.queryParams.date = this.parseTime(new Date(nextSevenDayTime));
		}, */
		getNextWeeks(){
			//获取当周日期
			let currentDate = new Date();
			let weeksDate = this.parseTime(currentDate,'{a}');
			let currentDateStr = this.parseTime(currentDate);
			if("日" == weeksDate){
				this.queryParams.weeks = this.getWeeks(currentDateStr) + 1;
				const oneDayMilliseconds = 24 * 60 * 60 * 1000;
				const nextSevenDayTime = currentDate.getTime() + oneDayMilliseconds * 7;
				this.queryParams.dateStr = this.parseTime(new Date(nextSevenDayTime));	
			}else{
				this.queryParams.weeks = this.getWeeks(currentDateStr);
				this.queryParams.dateStr = this.parseTime(currentDate);
			}
			this.queryParams.year = this.queryParams.dateStr.substr(0,4);
		},
		
		//导航栏时间选择
		dateChange(val){
			if(val){
				this.queryParams.weeks = this.getWeeks(val);
				this.queryParams.name = null;
				this.queryParams.year = this.queryParams.dateStr.substr(0,4);
			}else{
				this.getNextWeeks();
			}
			this.getList();
		},
		
		getWeeks(val){
			var year = val.substr(0,4);
			var month = val.substr(5,2);
			var day = val.substr(8,2);
			let weeks = this.getYearWeeks(year,month,day);
			return weeks;
		},
		
		chooseOne(e){
			this.onClickItem(e);
			this.$refs.showRight.close();
		},
		
		//点击名称切换数据
		onClickItem(e){
			this.current = e;
			this.childData = this.tableData[e].children;
			this.total = this.childData.length;
			this.choosePeople = this.tableData[e].name;
			//this.queryParams.name = this.choosePeople;
		},
		showDrawer() {
			this.$refs.showRight.open();
		},
		closeDrawer() {
			this.$refs.showRight.close();
		},
		//权限
		checkPermi,
		selectDictLabel,
		//获取数据
		async getList() {
			this.tableLoading = true;
			
			let response = await arrangeApi.listArrange(this.queryParams);
			let code = response.code;
			if(200 == code){
				let list = response.rows
				
				/* if (this.queryParams.pageNum > 1) {
					this.tableData = [...this.tableData, ...list]
				} else {
					this.tableData = list;
				} */
				
				this.tableData = list;
				
				//选项卡
				this.items = [];
				for(let val of list){
					this.items.push(val.name);
				}
				
				//选项卡子列表
				this.childData = this.tableData[this.current].children;
				this.total = this.childData.length;
				
				//选择角标
				this.choosePeople = this.tableData[this.current].name
			}
			
			if (this.tableData.length != this.total) {
				this.status = 'more';
			} else {
				this.status = 'no-more';
			}
			this.tableLoading = false;
		},


		/**
		 * 修改按钮操作
		 * @param {Object} row 数据
		 */
		handleUpdate(row) {
			this.$tab.navigateTo('/pages/module/arrange/index?formData=' + JSON.stringify(row));
		},
		/** 删除按钮操作 */
		handleDelete(row) {
			this.$modal.confirm('是否确认删除该数据项？').then(function () {
				return arrangeApi.delArrange(row.id);
			}).then( async () => {
				await this.getList();
				this.$modal.msgSuccess("删除成功");
			}).catch(() => {
			});
		},
		addArrange(){
			let mname = this.tableData[this.current].name;
			let userId = this.tableData[this.current].userId;
			let data = new Object();
			data.mname = mname;
			data.userId = userId;
			this.$tab.navigateTo('/pages/module/arrange/index?formData=' + JSON.stringify(data));
		},
		
		//下载模板
		downloadTemplate() {
			let downloadParams = this.queryParams;
			downloadParams.date = this.queryParams.dateStr;
			console.log("下载模板===========")
			download('/arrange/export',this.queryParams).then(data => {
				const platform = uni.getSystemInfoSync().uniPlatform;//
				console.log("当前平台类型，platform = " + platform);
				if("mp-weixin" != platform){
					
					//h5端
					let codeType = 'application/vnd.ms-excel;charset=UTF-8';
					if("ios" == platform){
						codeType = "charset=UTF-8";
					}
					try {
						// 通过返回的流数据 手动构建blob 流
					  const blob = new Blob([data],{
						type: codeType,
					  }) 
					  const aLink = document.createElement('a')
					  var fileName = "第" + this.queryParams.weeks + "周市领导下周工作预安排.xlsx";
					  fileName = fileName.replace(/\"/g, '')
					  aLink.style.display = 'none'
					  aLink.href = URL.createObjectURL(blob)
					  aLink.setAttribute('download', fileName) // 设置下载文件名称
					  document.body.appendChild(aLink)
					  aLink.click()
					  document.body.removeChild(aLink);
					  
					} catch (err) {
					  this.$modal.msg("下载文件出错，请重试！");
					}
					
				}else{
					
					//小程序端
					const fs = wx.getFileSystemManager(); //全局唯一的文件管理器
					console.log("当前设备类型 = " + fs);
					 fs.writeFile({
						  filePath: wx.env.USER_DATA_PATH +  "/第" + this.queryParams.weeks + "周市领导下周工作预安排.xlsx",   //这里填文件的名字
						  data: data,
						  encoding: "utf8",
						  success(res) {
							  uni.openDocument({  
								showMenu: true,
								filePath: wx.env.USER_DATA_PATH +  "/第" + this.queryParams.weeks + "周市领导下周工作预安排.xlsx",
								success: function(res) {
								   console.log('打开文档成功');
								 }
							  });
						  }
					 })
				}
			})
		},
		
		
	}
}
</script>

<style lang="scss">
	$nav-height: 30px;
page {
  background-color: #ffffff;
}

.example {
  padding: 15px;
  background-color: #fff;
}

.segmented-control {
  margin-bottom: 15px;
}

.button-group {
  margin-top: 15px;
  display: flex;
  justify-content: space-around;
}

.form-item {
  display: flex;
  align-items: center;
  flex: 1;
}

.button {
  display: flex;
  align-items: center;
  height: 35px;
  line-height: 35px;
  margin-left: 10px;
}

uni-card {
  font-size: 1px
}

.detailButton:after {
  border-color: black;
}

.bankLoanInfo {
  text-decoration: underline
}

.image {
  width: 80px;
  height: 80px !important;
  position: relative;
  left: 41%;
  margin-top: 50%;
}

.uni-body.noData {
  position: relative;
  left: 23.5%;
  color: #888;
  line-height: 620px;
}

.content {
  margin: 0 6px;
}
.card-actions-item-button{
	width:100%;
	text-align: center;
}

.uni-mt-10{
  // display: flex;
	position: -webkit-sticky;
	position: sticky;
	top: var(--window-top);
	z-index: 11;
	flex-direction: row;
	margin: 0px;
    background-color: white;
  		// padding: 15px 0 15px 0;
  		// border-bottom-style: solid;
  		// border-bottom-color: #E2E2E2;
}
.input-view {
	/* #ifndef APP-PLUS-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	// width: 500rpx;
	flex: 1;
	border-radius: 15px;
	flex-wrap: nowrap;
	line-height: $nav-height;
}
.city {
	/* #ifndef APP-PLUS-NVUE */
	display: flex;
	/* #endif */
	flex-direction: row;
	align-items: center;
	justify-content: flex-start;
	// width: 160rpx;
	margin-left: 20rpx;
}
.uni-nav-bar-text--underline{
	text-decoration: underline;
}
</style>
